package org.example.likou150.stack;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

// https://leetcode.cn/problems/evaluate-reverse-polish-notation/?envType=study-plan-v2&envId=top-interview-150
public class EvalRPN {
    public static void main(String[] args) {
        EvalRPN evalRPN=new EvalRPN();
        System.out.println(evalRPN.evalRPN(new String[]{"4","13","5","/","+"}));
    }

    public int evalRPN(String[] tokens) {
        LinkedList<Integer> linkedList=new LinkedList<>();
        for (String token : tokens) {
                if("+".equals(token)){
                    linkedList.addFirst(linkedList.removeFirst()+linkedList.removeFirst());
                }else if("-".equals(token)){
                    linkedList.addFirst(-linkedList.removeFirst()+linkedList.removeFirst());
                }else if("*".equals(token)){
                    linkedList.addFirst(linkedList.removeFirst()*linkedList.removeFirst());
                }else if("/".equals(token)){
                    int num1=linkedList.removeFirst();
                    int num2=linkedList.removeFirst();
                    linkedList.addFirst(num2/num1);
                }else {
                    linkedList.addFirst(Integer.valueOf(token));
                }
        }
        return linkedList.getFirst();
    }

//    public int evalRPN(String[] tokens) {
//        Stack<Integer> stack = new Stack<>();
//        for (String token : tokens) {
//            List<String> list = Arrays.asList("+", "-", "*", "/");
//            if(list.contains(token)){
//                Integer pop1 = stack.pop();
//                Integer pop2 = stack.pop();
//                if("+".equals(token)){
//                    stack.push(pop2+pop1);
//                }else if("-".equals(token)){
//                    stack.push(pop2-pop1);
//                }else if("*".equals(token)){
//                    stack.push(pop2*pop1);
//                }else if("/".equals(token)){
//                    stack.push(pop2/pop1);
//                }
//            } else {
//                stack.push(Integer.valueOf(token));
//            }
//        }
//        return stack.peek();
//    }
}
